package com.coolingme.dynamicproxy.jdkproxy;

import cn.hutool.core.lang.Console;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK媒婆，代理类
 *
 * @author wangyue
 * @date 2020/9/30 14:37
 */
public class JDkMatchMaker implements InvocationHandler {

    /**
     * 被代理人的引用
     */
    private IPerson target;

    public IPerson getInstance(IPerson person) {
        this.target = person;
        Class<? extends IPerson> clazz = this.target.getClass();
        return (IPerson) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // toString hashCode equals getClass等方法，无需走到执行SQL的流程
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        this.before(proxy, method, args);
        Object result = method.invoke(this.target, args);
        this.after(this.target);
        return result;
    }

    private void before(Object proxy, Method method, Object[] args) {
        Console.log("proxy:{} Method [{}.{} ({})]", proxy, target.getClass().getName(), method.getName(), args);

//        System.out.println("--------------------------------------");
//        System.out.println("媒婆开始咨询");
    }

    private void after(IPerson target) {
        System.out.println("--------------------------------------");

//        if (target instanceof PoolMan) {
//            System.out.println("媒婆：爪巴!");
//        } else if (target instanceof RichMan) {
//            System.out.println("媒婆：彳亍!");
//        } else {
//            System.out.println("媒婆：安排!");
//        }
    }

}
